using System;
using System.Globalization;
using System.IO;
using EnvDTE80;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Actions.Base;
using VSSDKAssist.Assets.Actions.General;
using VSSDKAssist.Assets.Enums;
using VSSDKAssist.Recipes.Common.Helpers;

namespace VSSDKAssist.Recipes.CreateVSPlkReport
{
	/// <summary>
	/// Action that creates a Plk analyzer report
	/// </summary>
	public class CreateVSPlkReportAction : ActionBase
	{
		private VSHive vsHive = VSHive.Experimental;

		/// <summary>
		/// Gets or sets the vs hive.
		/// </summary>
		/// <value>The vs hive.</value>
		[Input(Required = false)]
		public VSHive VSHive
		{
			get { return vsHive; }
			set { vsHive = value; }
		}

		private Type vsPackageType;

		/// <summary>
		/// Gets or sets the type of the VS package.
		/// </summary>
		/// <value>The type of the VS package.</value>
		[Input(Required = true)]
		public Type VSPackageType
		{
			get { return vsPackageType; }
			set { vsPackageType = value; }
		}

		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			using(ExecuteProcessAction executeProcessAction = new ExecuteProcessAction())
			{
				executeProcessAction.Site = this.Site;
				executeProcessAction.FileName =
					Path.Combine(CommonHelper.GetVSInstallPath(), Constants.DevEnv);

				string reportFilePath = Path.GetTempFileName();

				if(reportFilePath.Contains(" "))
				{
					reportFilePath = string.Concat("\"", reportFilePath, "\"");
				}

				string analyzeArgs = string.Format(
					CultureInfo.CurrentCulture,
					" /command tools.analyzepackage /analyzeargs {0} {1}",
					this.VSPackageType.GUID,
					reportFilePath);

				switch(this.vsHive)
				{
					case VSHive.Standard:
						executeProcessAction.Arguments = analyzeArgs;
						break;
					case VSHive.Experimental:
						executeProcessAction.Arguments = string.Concat(@"/rootSuffix Exp /RANU", analyzeArgs);
						break;
					default:
                        executeProcessAction.Arguments = string.Concat(@"/rootSuffix Exp /RANU", analyzeArgs);
						break;
				}

				executeProcessAction.Execute();

				if(File.Exists(reportFilePath))
				{
					VSSDKAssist.Assets.Helpers.OutputWindowHelper outputWindowHelper =
						new VSSDKAssist.Assets.Helpers.OutputWindowHelper(
							(DTE2)this.GetService<EnvDTE.DTE>(true), Properties.Resources.VSSDKAssistPane);

					outputWindowHelper.WriteMessage(File.ReadAllText(reportFilePath));

					File.Delete(reportFilePath);
				}
			}
		}
	}
}